<div class="layui-card">
    <div class="layui-card-header">
        <h2 class="header-title">用户管理</h2>
        <span class="layui-breadcrumb pull-right">
          <a href="#!console">首页</a>
          <a><cite>用户管理</cite></a>
        </span>
    </div>
    <div class="layui-card-body">
        <div class="layui-form toolbar">
            搜索：
            <select id="user-search-key">
                <option value="">-请选择-</option>
                <option value="user_id">ID</option>
                <option value="username">账号</option>
                <option value="nick_name">用户名</option>
                <option value="phone">手机号</option>
            </select>&emsp;
            <input id="user-search-value" class="layui-input search-input" type="text" placeholder="输入关键字"/>&emsp;
            <button id="user-btn-search" class="layui-btn icon-btn"><i class="layui-icon">&#xe615;</i>搜索</button>
            <button id="user-btn-add" class="layui-btn icon-btn"><i class="layui-icon">&#xe654;</i>添加</button>
        </div>

        <table class="layui-table" id="user-table" lay-filter="user-table"></table>
    </div>
</div>

<!-- 表单弹窗 -->
<script type="text/html" id="user-model">
    <form id="user-form" lay-filter="user-form" class="layui-form model-form">
        <input name="userId" type="hidden"/>
        <div class="layui-form-item">
            <label class="layui-form-label">账号</label>
            <div class="layui-input-block">
                <input name="username" placeholder="请输入账号" type="text" class="layui-input" maxlength="20"
                       lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">用户名</label>
            <div class="layui-input-block">
                <input name="nickName" placeholder="请输入用户名" type="text" class="layui-input" maxlength="20"
                       lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">手机号</label>
            <div class="layui-input-block">
                <input name="phone" placeholder="请输入手机号" type="text" class="layui-input" lay-verify="required|phone"
                       required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">性别</label>
            <div class="layui-input-block">
                <input type="radio" name="sex" value="男" title="男" checked/>
                <input type="radio" name="sex" value="女" title="女"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">角色</label>
            <div class="layui-input-block">
                <select name="roleId" lay-verify="required" p-each="roles">
                    <option p-bind="value:{{roleId}}">{{roleName}}</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item model-form-footer">
            <button class="layui-btn layui-btn-primary close" type="button">取消</button>
            <button class="layui-btn" lay-filter="user-form-submit" lay-submit>保存</button>
        </div>
    </form>
</script>

<!-- 表格操作列 -->
<script type="text/html" id="user-table-bar">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-xs" lay-event="reset">重置密码</a>
</script>

<!-- 表格状态列 -->
<script type="text/html" id="user-tpl-state">
    <input type="checkbox" lay-filter="user-tpl-state" value="{{d.userId}}" lay-skin="switch" lay-text="正常|锁定"
           {{d.state==0?'checked':''}}/>
</script>

<script>
    layui.use(['form', 'table', 'util', 'config', 'admin'], function () {
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var layer = layui.layer;
        var util = layui.util;
        var admin = layui.admin;

        // 渲染表格
        table.render({
            elem: '#user-table',
            url: 'user/query',
            method: 'post',
            where: {
                access_token: config.getToken().access_token
            },
            page: true,
            cols: [[
                {type: 'numbers'},
                {field: 'userId', title: 'ID'},
                {field: 'username', sort: true, title: '账号'},
                {field: 'nickName', sort: true, title: '用户名'},
                {field: 'phone', sort: true, title: '手机号'},
                {field: 'sex', sort: true, title: '性别'},
                {
                    sort: true, templet: function (d) {
                        return d.roles[0].roleName;
                    }, title: '角色'
                },
                {
                    sort: true, templet: function (d) {
                        return util.toDateString(d.createTime);
                    }, title: '创建时间'
                },
                {field: 'state', sort: true, templet: '#user-tpl-state', title: '状态'},
                {align: 'center', toolbar: '#user-table-bar', title: '操作'}
            ]]
        });

        // 添加按钮点击事件
        $('#user-btn-add').click(function () {
            showEditModel();
        });

        // 表单提交事件
        form.on('submit(user-form-submit)', function (data) {
            layer.load(2);
            admin.req('user', data.field, function (data) {
                layer.closeAll('loading');
                if (data.code == 200) {
                    layer.msg(data.msg, {icon: 1});
                    table.reload('user-table', {});
                    layer.closeAll('page');
                } else {
                    layer.msg(data.msg, {icon: 2});
                }
            }, $('#user-form').attr('method'));
            return false;
        });

        // 工具条点击事件
        table.on('tool(user-table)', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;

            if (layEvent === 'edit') { // 修改
                showEditModel(data);
            } else if (layEvent === 'reset') { // 重置密码
                doReSet(obj.data.userId);
            }
        });

        // 监听状态开关操作
        form.on('switch(user-tpl-state)', function (obj) {
            updateState(obj);
        });

        // 搜索按钮点击事件
        $('#user-btn-search').click(function () {
            doSearch();
        });

        //显示表单弹窗
        function showEditModel(data) {
            layer.open({
                type: 1,
                title: data ? '修改用户' : '添加用户',
                area: '450px',
                offset: '120px',
                content: $('#user-model').html(),
                success: function () {
                    $('#user-form')[0].reset();
                    $('#user-form').attr('method', 'POST');
                    var roleId = '';
                    if (data) {
                        roleId = data.roles[0].roleId;
                        form.val('user-form', data);
                        $('#user-form').attr('method', 'PUT');
                    }
                    getRoles(roleId);
                    $('#user-form .close').click(function () {
                        layer.closeAll('page');
                    });
                }
            });
        }

        // 获取所有角色
        var roles;
        var getRoles = function (value) {
            if (roles) {
                $('#user-form').vm({roles: roles});
                $('#user-form select[name=roleId]').val(value);
                form.render('select');
            } else {
                layer.load(2);
                admin.req('role', {}, function (data) {
                    layer.closeAll('loading');
                    if (0 == data.code) {
                        roles = data.data;
                        roles.unshift({roleId: '', roleName: '-请选择角色-'});
                        getRoles(value);
                    } else {
                        layer.msg('获取角色失败', {icon: 2});
                    }
                }, 'GET');
            }
        };

        // 更改状态
        var updateState = function (obj) {
            layer.load(2);
            var stateValue = obj.elem.checked ? 0 : 1;
            admin.req('user/state', {
                userId: obj.elem.value,
                state: stateValue
            }, function (data) {
                layer.closeAll('loading');
                if (data.code == 200) {
                    layer.msg(data.msg, {icon: 1});
                    //layui.table.reload('table-user', {});
                } else {
                    layer.msg(data.msg, {icon: 2});
                    $(obj.elem).prop('checked', !obj.elem.checked);
                    form.render('checkbox');
                }
            }, 'PUT');
        };

        // 搜索
        var doSearch = function () {
            var key = $('#user-search-key').val();
            var value = $('#user-search-value').val();
            if (value == '') {
                key = '';
            }
            table.reload('user-table', {where: {searchKey: key, searchValue: value}});
        };

        var doReSet = function (userId) {
            layer.confirm('确定重置此用户的密码吗？', function (i) {
                layer.close(i);
                layer.load(2);
                admin.req('user/psw/' + userId, {}, function (data) {
                    layer.closeAll('loading');
                    if (data.code == 200) {
                        layer.msg(data.msg, {icon: 1});
                    } else {
                        layer.msg(data.msg, {icon: 2});
                    }
                }, 'PUT');
            });
        }
    });
</script>